//
//  ICMBalanceViewController.m
//  ICrEAM
//
//  Created by kuroro on 16/11/25.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMBalanceViewController.h"
#import "ICMHeaderView.h"
#import "ICMProgressHeaderView.h"
#import "ICMBottomBarView.h"
#import "ICMBalanceInfoView.h"
#import "ICMBalanceInfoSKDView.h"
#import "ICMBalanceBasicInfoView.h"
#import "ICMBalanceMaintenanceAndPartsView.h"
#import "ICMBalanceAddCouponView.h"
#import "ICMBalanceUseCouponView.h"
#import "ICMBalanceRemoveFraction.h"
#import "MonitorViewController.h"
#import "ICMCarModel.h"
#import "ICMPersonerModel.h"
#import "ICMCustomerAndCarViewController.h"
#import "ICMProxyMemberModel.h"
#import "ICMProxyMemberSKDModel.h"
#import "ICMMemberView.h"
#import "AppDelegate.h"
#import "PopoverSelectionViewController.h"

#import "ICMBasicInfoModel.h"
#import "ICMAppointmentOtherInfoModel.h"
#import "ICMPartsTopModel.h"
#import "ICMActivityModel.h"
#import "ICMAppointmentPreviewViewController.h"

#import "ICMPictureModel.h"
#import "GetCarPreviewControllerViewController.h"

#import "ICMProxyActivityModel.h"
#import "ICMProxyPreviewViewController.h"
#import "ICMLevelView.h"

@interface ICMBalanceViewController ()<ICMHeaderViewDelegate,ICMBottomBarViewDelegate,UIScrollViewDelegate,ICMBalanceBasicInfoViewDelegate,ICMBalanceInfoViewDelegate,ICMBalanceInfoSKDViewDelegate,ICMProgressHeaderViewDelegate,AVAudioRecorderDelegate,ICMBalanceAddCouponViewDelegate>
@property (nonatomic, strong) UIScrollView *bigScrollView;
@property (nonatomic, strong) ICMHeaderView *headerView;
@property (nonatomic, strong) ICMProgressHeaderView *progressHeaderView;
@property (nonatomic, strong) ICMBottomBarView *bottomBarView;
@property (nonatomic, strong) ICMBalanceInfoView *balanceInfoView;       //结算信息（VW）
@property (nonatomic, strong) ICMBalanceInfoSKDView *balanceInfoSKDView; //结算信息 (SKD)
@property (nonatomic, strong) ICMBalanceAddCouponView *balanceAddCouponView; //增加优惠券
@property (nonatomic, strong) ICMMemberView *memberView;//会员信息
@property (nonatomic, strong) NSString *isUse;  //验证码开关
@property (nonatomic, assign) BOOL isAuthorization; // 是否关爱总监
@property (nonatomic, strong) ICMLevelView *levelView; //用户权限页面
@property (nonatomic, strong) UIView *blankView;


@property (nonatomic, strong) ICMBalanceBasicInfoView *balanceBasicInfoView;
@property (nonatomic, strong) ICMBalanceMaintenanceAndPartsView *maintenanceAndPartsView;
@property (nonatomic, strong) ICMCarModel *carModel; //车辆model
@property (nonatomic, strong) ICMPersonerModel *personerModel; //车主model
@property (nonatomic, strong) NSMutableArray *selectedDataArray;
//赠送优惠券金额
@property (nonatomic, strong) ICMBalanceUseCouponView *couponViewController;

//录音
@property (nonatomic, strong) AVAudioRecorder *audioRecorder;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic, assign) BOOL couldRecord;
@property (nonatomic, assign) BOOL haveRecord;
@property (nonatomic, assign) BOOL isPrinted;
@property (nonatomic, strong) NSString *file;

//顶部进度条字典
@property (nonatomic, strong) NSMutableDictionary *progressDic;

//界面值是否改变
@property (nonatomic, assign) BOOL hasViewValueChanged;
@property (nonatomic, assign) BOOL isAccount;
@end

@implementation ICMBalanceViewController

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
}

- (void)addProgressHeaderView{
    [self.progressHeaderView removeFromSuperview];
    self.progressHeaderView = [ICMProgressHeaderView createProgressHeaderViewWithStateDic:self.progressDic andFrame:CGRectMake(0, 40, ScreenWidth, 66)];
    self.progressHeaderView.delegate = self;
    [self.view  insertSubview:self.progressHeaderView belowSubview:self.suspendView];
}

/*ICMProgressHeaderViewDelegate*/
- (void)progressHeaderViewDidSelectedIndex:(NSInteger)index{
    if(index == 0)
    {
        //预约预览
        if(self.basicModel.BOOKING_ORDER_NO && ![self.basicModel.BOOKING_ORDER_NO isEqualToString:@""])
        {
            NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
            [parameters setObject:self.basicModel.BOOKING_ORDER_NO forKey:@"ORDER_ID"];
            ICMRequestManager *manager = [[ICMRequestManager alloc]init];
            [manager startGetRequestWithURL:BookingOrderDetils parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
                if ([data[@"CODE"] integerValue] == 200) {
                    if (IsArr(data[@"TT_BOOKING_OEDER"])) {
                        ICMAppointmentBasicInfoModel *tempBasicInfoModel = [ICMAppointmentBasicInfoModel yy_modelWithDictionary:data[@"TT_BOOKING_OEDER"][0]];
                        ICMAppointmentOtherInfoModel *tempBasicOtherModel = [ICMAppointmentOtherInfoModel yy_modelWithDictionary:data[@"TT_BOOKING_OEDER"][0]];
                        ICMPartsTopModel *tempPartsTopModel = [ICMPartsTopModel yy_modelWithDictionary:data[@"TT_BOOKING_OEDER"][0]];
                        
                        ICMRepairMaintenancesModel *tempMaintenancesModel = [ICMRepairMaintenancesModel yy_modelWithDictionary:data];
                        [tempMaintenancesModel createRepairMaintenanceBookingModel];
                        
                        ICMRepairPartsArrayModel *tempPartsArrayModel = [ICMRepairPartsArrayModel yy_modelWithDictionary:data];
                        [tempPartsArrayModel createRepairPartsBookingModel];
                        
                        ICMActivityModel *tempActivityModel = [ICMActivityModel yy_modelWithDictionary:data];
                        [tempActivityModel createActivityItemBookingModel];
                        
                        ICMAppointmentPreviewViewController *PVC = [[ICMAppointmentPreviewViewController alloc]init];
                        PVC.basicInfoModel = tempBasicInfoModel;
                        PVC.basicOtherModel = tempBasicOtherModel;
                        PVC.partsTopModel = tempPartsTopModel;
                        PVC.maintenancesModel = tempMaintenancesModel;
                        PVC.partsArrayModel = tempPartsArrayModel;
                        PVC.activityModel = tempActivityModel;
                        [self.navigationController pushViewController:PVC animated:YES];
                    }
                    
                }
            }];
        }
    }
    if(index == 1)
    {
        //接车预览
        if(self.basicModel.RECEPTION_NO && ![self.basicModel.RECEPTION_NO isEqualToString:@""])
        {
            NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
            [parameters setObject:self.basicModel.RECEPTION_NO forKey:@"RECEPTION_NO"];
            ICMRequestManager *manager = [[ICMRequestManager alloc]init];
            [manager startGetRequestWithURL:ReceptionVehicleOrderDetils parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
                if ([data[@"CODE"] integerValue] == 200) {
                    NSMutableArray *imageModels = [NSMutableArray array];
                    if (IsArr(data[@"TT_RECPTION_DAMANGE"])) {
                        NSArray *images = data[@"TT_RECPTION_DAMANGE"];
                        for (NSDictionary *dic in images) {
                            ICMPictureModel *model = [ICMPictureModel yy_modelWithDictionary:dic];
                            [imageModels addObject:model];
                        }
                    }
                    
                    GetCarPreviewControllerViewController *GCP = [GetCarPreviewControllerViewController new];
                    
                    if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                        ICMBasicInfoModel *infoModel = [ICMBasicInfoModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
                        GCP.basicInfoModel = infoModel;
                    }
                    if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                        ICMCarePackageDownModel *carePackageDownModel = [ICMCarePackageDownModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
                        GCP.carePackageDownModel = carePackageDownModel;
                    }
                    if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                        ICMCheckAppearanceDownModel *checkAppearanceDownModel = [ICMCheckAppearanceDownModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
                        GCP.checkAppearanceDownModel = checkAppearanceDownModel;
                    }
                    if (IsArr(data[@"TT_RECEPTION_VEHICLE_ORDER"])) {
                        ICMPartsTopModel *partsTopModel = [ICMPartsTopModel yy_modelWithDictionary:data[@"TT_RECEPTION_VEHICLE_ORDER"][0]];
                        GCP.partsTopModel = partsTopModel;
                    }
                    
                    ICMCarePackageModel *carePackageModel = [ICMCarePackageModel yy_modelWithDictionary:data];
                    [carePackageModel createCarePackageItemModel];
                    GCP.carePackageModel = carePackageModel;
                    
                    ICMRepairMaintenancesModel *repairMaintenanceModel = [ICMRepairMaintenancesModel yy_modelWithDictionary:data];
                    [repairMaintenanceModel createRepairMaintenanceModel];
                    
                    ICMRepairPartsArrayModel *repairPartsModel = [ICMRepairPartsArrayModel yy_modelWithDictionary:data];
                    [repairPartsModel createRepairPartsModel];
                    
                    ICMActivityModel *activityModel = [ICMActivityModel yy_modelWithDictionary:data];
                    [activityModel createActivityItemModel];
                    
                    ICMCheckAppearanceTopModel *checkAppearanceTopModel = [ICMCheckAppearanceTopModel yy_modelWithDictionary:data];
                    [checkAppearanceTopModel createPictureModel];
                    
                    GCP.repairEventModel = repairMaintenanceModel;
                    GCP.repairPartsModel = repairPartsModel;
                    GCP.activityModel = activityModel;
                    GCP.checkAppearanceTopModel = checkAppearanceTopModel;
                    [self.navigationController pushViewController:GCP animated:YES];        }
            }];
        }
    }
    if(index == 2)
    {
        //委托书预览
        if(self.basicModel.RO_NO && ![self.basicModel.RO_NO isEqualToString:@""])
        {
            NSMutableArray *activityModels = [[NSMutableArray alloc] init];
            NSMutableArray *activityTempModels = [[NSMutableArray alloc] init];
            [activityModels removeAllObjects];
            [activityTempModels removeAllObjects];
            NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
            [parameters setObject:self.basicModel.RO_NO forKey:@"RO_NO"];
            ICMRequestManager *manager = [[ICMRequestManager alloc]init];
            [manager startGetRequestWithURL:RepairOrderDetils parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
                
                ICMProxyBasicInfoModel *basicModel = [[ICMProxyBasicInfoModel alloc]init];
                if (IsArr(data[@"TT_REPAIR_ORDER"])) {
                    basicModel = [ICMProxyBasicInfoModel yy_modelWithDictionary:data[@"TT_REPAIR_ORDER"][0]];
                }
                ICMRepairMaintenancesModel *repairMaintenancesModel = [ICMRepairMaintenancesModel yy_modelWithDictionary:data];
                [repairMaintenancesModel createRepairMaintenanceRoModel];
                ICMRepairPartsArrayModel *repairPartsArrayModel = [ICMRepairPartsArrayModel yy_modelWithDictionary:data];
                [repairPartsArrayModel createRepairPartsRoModel];
                
                NSArray *dataArray = data[@"TT_ACTIVITY"];
                __block int countIndex = 0;
                if(dataArray && dataArray.count > 0)
                {
                    if (dataArray.count != 0 && dataArray) {
                        
                        for (NSDictionary *activityData in dataArray) {
                            ICMProxyActivityViewModel *model = [[ICMProxyActivityViewModel alloc]init];
                            model.title = activityData[@"ACTIVITY_NAME"];
                            model.type = activityData[@"ACTIVITY_TYPE"];
                            model.subTitle = activityData[@"ACTIVITY_CODE"];
                            model.startTime = [ICrEAMTool getDateWithTimeInterval:activityData[@"SALES_DATE_BEGIN"]];
                            model.endTime = [ICrEAMTool getDateWithTimeInterval:activityData[@"SALES_DATE_END"]];
                            //ischecked 判断
                            if(activityData[@"IS_CHECKED"])
                            {
                                model.IS_CHECKED = activityData[@"IS_CHECKED"];
                            }
                            else
                            {
                                model.IS_CHECKED = ICMEnumIntToString(ICMEnumYESOrNONO);
                            }
                            [activityModels addObject:model];
                        }
                        for (ICMProxyActivityViewModel *viewModel in activityModels) {
                            
                            ICMProxyActivityViewModel *temp = [[ICMProxyActivityViewModel alloc]init];
                            temp.title = viewModel.title;
                            temp.type = viewModel.type;
                            temp.subTitle = viewModel.subTitle;
                            temp.startTime = viewModel.startTime;
                            temp.endTime = viewModel.endTime;
                            temp.IS_CHECKED = viewModel.IS_CHECKED;
                            [activityTempModels addObject:temp];
                            
                            if(viewModel.subTitle)
                            {
                                //去除首位空格和换行
                                viewModel.subTitle = [viewModel.subTitle stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                                NSString *url = [NSString stringWithFormat:@"/INFO_ICREAM_WEB/App/queryActivityDetail?ACTIVITY_CODE=%@",viewModel.subTitle];
                                [[[ICMRequestManager alloc] init]startGetRequestWithURL:url parameters:nil inHudView:self.view andResultBlock:^(id data, NSString *failText) {
                                    countIndex++;
                                    if (!failText) {
                                        NSArray *labelArray = data[@"TT_ACTIVITY_LABOUR"];
                                        NSArray *partsArray = data[@"TT_ACTIVITY_PART"];
                                        for (NSDictionary *labourDic in labelArray) {
                                            ICMProxyActivityLabourModel *labelModel = [ICMProxyActivityLabourModel yy_modelWithJSON:labourDic];
                                            [viewModel.allActivityModel.TT_ACTIVITY_LABOUR addObject:labelModel];
                                            
                                            ICMRepairMaintenanceModel *labourTempModel = [ICMRepairMaintenanceModel yy_modelWithJSON:labourDic];
                                            [temp.allActivityModel.TT_ACTIVITY_LABOUR addObject:labourTempModel];
                                        }
                                        for (NSDictionary *partDic in partsArray) {
                                            ICMProxyActivityPartsModel *partsModel = [ICMProxyActivityPartsModel yy_modelWithJSON:partDic];
                                            [viewModel.allActivityModel.TT_ACTIVITY_PART addObject:partsModel];
                                            
                                            ICMRepairPartsModel *partsTempModel = [ICMRepairPartsModel yy_modelWithJSON:partDic];
                                            [temp.allActivityModel.TT_ACTIVITY_PART addObject:partsTempModel];
                                        }
                                        
                                    }else{
                                        
                                    }
                                    if(countIndex == dataArray.count)
                                    {
                                        //跳转
                                        ICMProxyPreviewViewController *PVC = [[ICMProxyPreviewViewController alloc]init];
                                        PVC.activityModels = activityTempModels;
                                        PVC.repairMaintenancesModel = repairMaintenancesModel;
                                        PVC.proxyBasicInfoModel = basicModel;
                                        PVC.repairPartsArrayModel = repairPartsArrayModel;
                                        [self.navigationController pushViewController:PVC animated:YES];
                                    }
                                }];
                            }
                            
                        }
                    }
                }
                else
                {
                    //跳转
                    ICMProxyPreviewViewController *PVC = [[ICMProxyPreviewViewController alloc]init];
                    PVC.activityModels = activityTempModels;
                    PVC.repairMaintenancesModel = repairMaintenancesModel;
                    PVC.proxyBasicInfoModel = basicModel;
                    PVC.repairPartsArrayModel = repairPartsArrayModel;
                    [self.navigationController pushViewController:PVC animated:YES];
                }
                
                
            }];
        }
    }
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"结算";
    self.haveRecord = NO;
    self.isPrinted = YES;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = BackgroundColor_White;
    self.headerView = [ICMHeaderView createHeaderViewWithFrame:CGRectMake(0, 0, ScreenWidth, 40) andTitles:@[@"基本信息",@"项目和零件",@"结算信息"] andType:@"0"];
    self.headerView.delegate = self;
    [self.view addSubview:self.headerView];
    
    self.progressDic = [@{@"0":self.basicModel.BOOKING_ORDER_NO?:@"",@"1":self.basicModel.RECEPTION_NO?:@"",@"2":self.basicModel.RO_NO?:@"",@"3":@""}mutableCopy];
    [self addProgressHeaderView];
    
    _bottomBarView = [ICMBottomBarView createBottomBarViewWithTitles:@[@"录 音",@"赠送优惠券",@"优惠券折扣",@"去零",@"结算",@"打印"] normalImages:@[[UIImage imageNamed:@"btn_record"],[UIImage imageNamed:@"bottom_btn_coupon"],[UIImage imageNamed:@"bottom_btn_usecoupon"],[UIImage imageNamed:@"bottom_btn_quling"],[UIImage imageNamed:@"bottom_btn_balance"],[UIImage imageNamed:@"bottom_btn_print"]] seletedImages:nil andFrame:CGRectMake(0, ScreenHeight-70-NavBarAndStatusHeight, ScreenWidth, 70)];
    _bottomBarView.delegate = self;
    [_bottomBarView setButtonDisEnable:5];
    if ([self.basicModel.RO_REPAIR_TYPE_NAME isEqualToString:@"质量担保保养"]){
        [_bottomBarView setButtonDisEnable:2];
    }
    
    [self.view addSubview:_bottomBarView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentVC:) name:@"popoverSelectionView" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewValueChanged:) name:@"BalanceViewValueChanged" object:nil];
    [self setupBigScrollView];
    [self setAudioAndPlayer];
    //头部跳转用赋值
    super.super_VIN = self.basicModel.VIN;
    super.super_owner_no = self.basicModel.OWNER_NO;
    [self clickMonitorBtn];
    
    
}



- (void)setupBigScrollView{
    self.bigScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake( 0, self.progressHeaderView.bottomEdge, ScreenWidth, ScreenHeight-176-NavBarAndStatusHeight)];
    
    self.bigScrollView.contentSize = CGSizeMake(ScreenWidth*3, ScreenHeight-240);
    //
    self.balanceBasicInfoView = [ICMBalanceBasicInfoView createICMBalanceBasicInfoViewWithFrame:CGRectMake(0, 0, ScreenWidth, CGRectGetHeight(self.bigScrollView.frame))];
    [self.balanceBasicInfoView setBasicInfoViewWithModel:self.basicModel];
    self.balanceBasicInfoView.delegate = self;
    
    if ([ICrEAMTool isVW]) {
        self.balanceInfoView = [ICMBalanceInfoView createICMBalanceInfoViewWithFrame:CGRectMake(2*ScreenWidth, 0, ScreenWidth, CGRectGetHeight(self.bigScrollView.frame))];
        self.balanceInfoView.delegate = self;
        [self.balanceInfoView setBalanceInfoViewWithModel:self.basicModel];
        [self.bigScrollView addSubview:self.balanceInfoView];
    }else{
        self.balanceInfoSKDView = [ICMBalanceInfoSKDView createICMBalanceInfoSKDViewWithFrame:CGRectMake(2*ScreenWidth, 0, ScreenWidth, CGRectGetHeight(self.bigScrollView.frame))];
        [self.balanceInfoSKDView setBalanceInfoViewWithModel:self.basicModel];
        self.balanceInfoSKDView.delegate = self;
        [self.bigScrollView addSubview:self.balanceInfoSKDView];
    }
    
    self.maintenanceAndPartsView = [ICMBalanceMaintenanceAndPartsView createICMMaintenanceAndPartsViewWithFrame:CGRectMake(ScreenWidth, 0, ScreenWidth, CGRectGetHeight(self.bigScrollView.frame))];
    self.maintenanceAndPartsView.delegate = self;
    //    basicModel必须第一个赋值
    [self.maintenanceAndPartsView setupPartsViewWithBasicModel:self.basicModel];
    //    材料第二个赋值
    [self.maintenanceAndPartsView setupPartsViewWithRepairPartsArrayModel:self.repairPartsArrayModel];
    [self.maintenanceAndPartsView setupPartsViewWithRepairMaintenancesModel:self.repairMaintenancesModel];
    
    [self.bigScrollView addSubview:self.balanceBasicInfoView];
    
    [self.bigScrollView addSubview:self.maintenanceAndPartsView];
    //
    self.bigScrollView.pagingEnabled = YES;
    self.bigScrollView.delegate = self;
    self.bigScrollView.showsHorizontalScrollIndicator = NO;
    
    [self.view addSubview:self.bigScrollView];
    
}





/**********************UIScrollViewDelegate***************************/
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    float offsetX = scrollView.contentOffset.x;
    self.headerView.selectedIndex = offsetX/ScreenWidth;
}

/**********************ICMHeaderViewDelegate***************************/
- (void)headerViewDidSelectedButtonAtIndex:(NSInteger)index{
    [self.bigScrollView scrollRectToVisible:CGRectMake(ScreenWidth*index, 0, ScreenWidth, ScreenHeight-240) animated:YES];
}

#pragma mark -- 底部按钮逻辑
/**********************ICMBottomBarViewDelegate***************************/
- (void)bottomBarViewDidSelectIndex:(NSInteger)index{
    
    if (index == 1) {
        ICMBalanceAddCouponView *couponViewController = [[ICMBalanceAddCouponView alloc]initWithFrame:Window.bounds];
        couponViewController.delegate = self;
        couponViewController.OWNER_NO = self.basicModel.OWNER_NO;
        couponViewController.OWNER_NAME = self.basicModel.OWNER_NAME;
        self.balanceAddCouponView = couponViewController;
        [Window addSubview:couponViewController];
    } else if (index == 2) {
        if (!self.couponViewController) {
            ICMBalanceUseCouponView *couponViewController = [[ICMBalanceUseCouponView alloc]initWithFrame:Window.bounds];
            couponViewController.OWNER_NO = self.basicModel.OWNER_NO;
            couponViewController.labourRealPrice = [ICrEAMTool isVW]?self.balanceInfoView.labourRealPrice.subtitleLabel.text : self.balanceInfoSKDView.labourRealPrice.subtitleLabel.text;
            couponViewController.partRealPrice = [ICrEAMTool isVW]?self.balanceInfoView.partRealPrice.subtitleLabel.text : self.balanceInfoSKDView.partRealPrice.subtitleLabel.text;
            self.couponViewController = couponViewController;
        }
        [self getData:self.basicModel.OWNER_NO];
        [Window addSubview:self.couponViewController];
    } else if (index == 3) {
        ICMBalanceRemoveFraction *fractionViewController = [[ICMBalanceRemoveFraction alloc]initWithFrame:Window.bounds];
        fractionViewController.amoutStr = [ICrEAMTool isVW]?self.balanceInfoView.accounts.desc:self.balanceInfoSKDView.accounts.desc;
        [Window addSubview:fractionViewController];
    }
    else if (index == 4) {
        if ([self checkFormData]) {
            if ([self.isUse isEqualToString:@"0"] && !self.isAuthorization) {
                [Window addSubview:self.blankView];
                self.levelView.titlelabel.text = @"关爱总监授权";
                [Window addSubview:self.levelView];
            }else{
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确认进行结算？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
                [alert show];
            }
        }
    }
    
    else if (index == 5) {
        //打印
        if(self.jiesuanNO && ![self.jiesuanNO isEqualToString:@""])
        {
            self.isPrinted = YES;
            [ICrEAMTool ipadPrintWithPrintType:BalancePrintType printId:self.jiesuanNO Controller:self andEstimatePrice:nil];
        }
    }
    else if (index == 0){
        if(self.haveRecord == NO){
            [self.view showString:@"录音开始" forSeconds:1.5];
            self.bottomBarView.recorderLabel.text = @"暂 停";
            [self clickRecordBtn];
            self.haveRecord = YES;
        }else{
            self.bottomBarView.recorderLabel.text = @"录 音";
            [self.view showString:@"录音暂停" forSeconds:1.5];
            [self clickPauseBtn];
            self.haveRecord = NO;
            
            
        }
    }
}


- (void)backButtonClick {
    if(_isAccount == NO &&_hasViewValueChanged == YES){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否放弃当前数据？" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        alert.tag = 101;
        [alert show];
    
    }
    
    
//    if(self.hasViewValueChanged)
//    {
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否放弃当前数据？" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
//        alert.tag = 101;
//        [alert show];
//    }
    
    else if (!self.isPrinted) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"结算单未打印，确认返回？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
        [alert show];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


- (void)presentVC:(NSNotification *)notification {
    [self presentViewController:[notification object] animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -- basicInfo点击
//点击监控信息按钮
- (void)clickMonitorBtn{
    if (self.basicModel.VIN) {
        MonitorViewController *mvc = [[MonitorViewController alloc] init];
        mvc.vin = self.basicModel.VIN;
        //        [self.navigationController pushViewController:mvc animated:YES];
        mvc.modalPresentationStyle=UIModalPresentationFormSheet;
        [self presentViewController:mvc animated:YES completion:nil];
    }
}
//点击车辆信息
- (void)clickCarInfoBtn{
    if (self.basicModel.VIN && self.basicModel.OWNER_NO) {
        [self getInfoWithOWNER_NO:self.basicModel.OWNER_NO orVin:self.basicModel.VIN type:@"1"];
    }
}
//点击车主信息
- (void)clickCarOwnerBtn{
    if (self.basicModel.VIN && self.basicModel.OWNER_NO) {
        [self getInfoWithOWNER_NO:self.basicModel.OWNER_NO orVin:self.basicModel.VIN type:@"0"];
    }
}

#pragma mark -- 获取上传model
- (void)getICMBalanceLabourModels
{
    [self.labourModelArray removeAllObjects];
    for(int i = 0;i<self.repairMaintenancesModel.TT_RO_LABOUR.count;i++)
    {
        ICMRepairMaintenanceModel *oldModel = self.repairMaintenancesModel.TT_RO_LABOUR[i];
        ICMBalanceLabourModel *model = [[ICMBalanceLabourModel alloc] init];
        model.RO_ITEM_ID = oldModel.ITEM_ID;
        model.LABOUR_PRICE = oldModel.LABOUR_PRICE?:@"0";
        model.STD_LABOUR_HOUR = oldModel.STD_LABOUR_HOUR;
        model.DISCOUNT = [NSString stringWithFormat:@"%.2f",oldModel.DISCOUNT];
        model.DISCOUNT_AMOUNT = [NSString stringWithFormat:@"%.2f",[oldModel.LABOUR_AMOUNT doubleValue] * (1-oldModel.DISCOUNT)];
        model.DISCOUNT_STD_LABOUR_HOUR =  [NSString stringWithFormat:@"%.2f",[model.STD_LABOUR_HOUR doubleValue] * (oldModel.DISCOUNT)];
        model.IS_DISCOUNT = oldModel.isDiscount?ICMEnumIntToString(ICMEnumYESOrNONO):ICMEnumIntToString(ICMEnumYESOrNOYES);
        model.REAL_RECEIVE_AMOUNT = [NSString stringWithFormat:@"%.2f",[oldModel.LABOUR_AMOUNT doubleValue] * (oldModel.DISCOUNT)];
        model.SB_CAL_TAG = ICMEnumIntToString(ICMEnumYESOrNONO);
        if ([self.basicModel.RO_REPAIR_TYPE_NAME isEqualToString:@"质量担保保养"] && i == 0){
            model.STD_LABOUR_HOUR = self.maintenanceAndPartsView.workingTime;
            model.DISCOUNT = @"1.00";
            model.DISCOUNT_AMOUNT = @"0";
            model.DISCOUNT_STD_LABOUR_HOUR = @"0";
            model.SB_CAL_TAG = ICMEnumIntToString(ICMEnumYESOrNOYES);
            model.REAL_RECEIVE_AMOUNT = self.maintenanceAndPartsView.workingPrice;
        }
        [self.labourModelArray addObject:model];
    }
}
- (void)getICMBalanceLabourPayObjModels
{
    [self.labourPayObjModelArray removeAllObjects];
    for(int i = 0;i<self.repairMaintenancesModel.TT_RO_LABOUR.count;i++)
    {
        ICMRepairMaintenanceModel *oldModel = self.repairMaintenancesModel.TT_RO_LABOUR[i];
        ICMBalanceLabourPayObjModel *model = [[ICMBalanceLabourPayObjModel alloc] init];
        model.PAYMENT_OBJECT_CODE = self.basicModel.OWNER_NO;
        model.PAYMENT_OBJECT_NAME = self.basicModel.OWNER_NAME;
        model.RECEIVEABLE_AMOUNT = oldModel.LABOUR_AMOUNT;
        model.REAL_RECEIVE_AMOUNT = [NSString stringWithFormat:@"%.2f",[oldModel.LABOUR_AMOUNT doubleValue] * oldModel.DISCOUNT];
        model.DISCOUNT = [NSString stringWithFormat:@"%.2f",oldModel.DISCOUNT];
        model.DISCOUNT_AMOUNT = [NSString stringWithFormat:@"%.2f",[oldModel.LABOUR_AMOUNT doubleValue] * (1-oldModel.DISCOUNT)];
        model.ITEM_ID = oldModel.ITEM_ID;
        if ([self.basicModel.RO_REPAIR_TYPE_NAME isEqualToString:@"质量担保保养"]) {
            model.PAYMENT_OBJECT_CODE = @"999999999999";
            model.PAYMENT_OBJECT_NAME = @"上汽大众";
            if (i == 0) {
                model.RECEIVEABLE_AMOUNT = self.maintenanceAndPartsView.workingPrice;
                model.REAL_RECEIVE_AMOUNT = self.maintenanceAndPartsView.workingPrice;
                model.DISCOUNT_AMOUNT = 0;
                
            }
        }
        [self.labourPayObjModelArray addObject:model];
    }
}

- (void)getICMBalanceRepairPartModels
{
    [self.repairPartModelArray removeAllObjects];
    for(int i = 0;i<self.repairPartsArrayModel.TT_RO_REPAIR_PART.count;i++)
    {
        ICMRepairPartsModel *oldModel = self.repairPartsArrayModel.TT_RO_REPAIR_PART[i];
        ICMBalanceRepairPartModel *model = [[ICMBalanceRepairPartModel alloc] init];
        model.RO_ITEM_ID = oldModel.ITEM_ID;
        model.PART_QUANTITY = oldModel.OBLIGATED_QUANTITY;
        model.PART_SALES_PRICE = oldModel.SALES_PRICE;
        model.PART_SALES_AMOUNT = oldModel.PART_SALES_AMOUNT;
        model.DISCOUNT = [NSString stringWithFormat:@"%.2f",oldModel.DISCOUNT];
        model.DISCOUNT_AMOUNT =  [NSString stringWithFormat:@"%.2f",[oldModel.PART_SALES_AMOUNT doubleValue] * (1-oldModel.DISCOUNT)];
        model.REAL_RECEIVE_AMOUNT = [NSString stringWithFormat:@"%.2f",[oldModel.PART_SALES_AMOUNT doubleValue] * (oldModel.DISCOUNT)];
        model.IS_DISCOUNT = oldModel.isDiscount?ICMEnumIntToString(ICMEnumYESOrNONO):ICMEnumIntToString(ICMEnumYESOrNOYES);
        
        [self.repairPartModelArray addObject:model];
    }
}

- (void)getICMBalanceRepairPartPayObjModels
{
    [self.repairPartPayObjModelArray removeAllObjects];
    for(int i = 0;i<self.repairPartsArrayModel.TT_RO_REPAIR_PART.count;i++)
    {
        ICMRepairPartsModel *oldModel = self.repairPartsArrayModel.TT_RO_REPAIR_PART[i];
        ICMBalanceRepairPartPayObjModel *model = [[ICMBalanceRepairPartPayObjModel alloc] init];
        model.PAYMENT_OBJECT_CODE = self.basicModel.OWNER_NO;
        model.PAYMENT_OBJECT_NAME = self.basicModel.OWNER_NAME;
        if ([self.basicModel.RO_REPAIR_TYPE_NAME isEqualToString:@"质量担保保养"]) {
            model.PAYMENT_OBJECT_CODE = @"999999999999";
            model.PAYMENT_OBJECT_NAME = @"上汽大众";
        }
        model.RECEIVEABLE_AMOUNT = oldModel.PART_SALES_AMOUNT;
        model.REAL_RECEIVE_AMOUNT = [NSString stringWithFormat:@"%.2f",[oldModel.PART_SALES_AMOUNT doubleValue] * (oldModel.DISCOUNT)];
        model.DISCOUNT = [NSString stringWithFormat:@"%.2f",oldModel.DISCOUNT];;
        model.DISCOUNT_AMOUNT = [NSString stringWithFormat:@"%.2f",[oldModel.PART_SALES_AMOUNT doubleValue] * (1-oldModel.DISCOUNT)];
        model.ITEM_ID = oldModel.ITEM_ID;
        
        [self.repairPartPayObjModelArray addObject:model];
    }
    
}

- (void)getICMBalanceCustomerCoupons
{
    [self.customerCouponArray removeAllObjects];
    for(int i = 0;i<self.couponViewController.selectedDataArray.count;i++)
    {
        ICMBalanceCouponModel *oldModel = self.couponViewController.selectedDataArray[i];
        ICMBalanceCustomerCoupon *model = [[ICMBalanceCustomerCoupon alloc] init];
        model.UPDATE_STATUS = @"A";
        model.ITEM_ID = oldModel.ITEM_ID;
        model.COUPON_TYPE = oldModel.COUPON_TYPE;
        model.COUPON_UVAL = oldModel.COUPON_UVAL;
        model.COUPON_QUANTITY = oldModel.COUPON_QUANTITY;
        
        [self.customerCouponArray addObject:model];
    }
}

- (NSMutableArray *)labourModelArray
{
    if(!_labourModelArray)
    {
        _labourModelArray = [[NSMutableArray alloc] init];
    }
    return _labourModelArray;
}

- (NSMutableArray *)labourPayObjModelArray
{
    if(!_labourPayObjModelArray)
    {
        _labourPayObjModelArray = [[NSMutableArray alloc] init];
    }
    return _labourPayObjModelArray;
}

- (NSMutableArray *)repairPartModelArray
{
    if(!_repairPartModelArray)
    {
        _repairPartModelArray = [[NSMutableArray alloc] init];
    }
    return _repairPartModelArray;
}

- (NSMutableArray *)repairPartPayObjModelArray
{
    if(!_repairPartPayObjModelArray)
    {
        _repairPartPayObjModelArray = [[NSMutableArray alloc] init];
    }
    return _repairPartPayObjModelArray;
}

- (NSMutableArray *)customerCouponArray
{
    if(!_customerCouponArray)
    {
        _customerCouponArray = [[NSMutableArray alloc] init];
    }
    return _customerCouponArray;
}


#pragma mark -- 接口
- (void)uploadMusic{
    
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    [manager startPostMusicWithURL:nil parameters:nil musicUrl:[NSURL fileURLWithPath:micTempPath] inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if (failText) {
            [self.view showString:@"录音上传失败" forSeconds:1.5];
            [self performSelector:@selector(runBalance) withObject:nil afterDelay:1.5];
            
            return ;
        }
        if ([data[@"CODE"] integerValue] == 200) {
            self.file = data[@"FILE"]?:@"";
            [self performSelector:@selector(runBalance) withObject:nil afterDelay:1.5];
            
            [self.view showString:@"录音上传成功" forSeconds:1.5];
            
            self.haveRecord = NO;
            
        }else{
            [self.view showString:@"录音上传失败" forSeconds:1.5];
            [self performSelector:@selector(runBalance) withObject:nil afterDelay:1.5];
        }
        
    }];
}


- (void)getInfoWithOWNER_NO:(NSString *)OWNER_NO orVin:(NSString *)vin type:(NSString *)type{
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:OWNER_NO forKey:@"OWNER_NO"];
    [parameters setObject:vin forKey:@"VIN"];
    [manager startGetRequestWithURL:QueryOwnerDetail parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        self.carModel = [ICMCarModel yy_modelWithDictionary:data[@"TM_VEHICLE"][0]];
        self.personerModel = [ICMPersonerModel yy_modelWithDictionary:data[@"TM_OWNER"][0]];
        ICMCustomerAndCarViewController *customerAndCar = [ICMCustomerAndCarViewController new];
        customerAndCar.carModel = self.carModel;
        customerAndCar.personerModel = self.personerModel;
        customerAndCar.entrance = [type integerValue];
        [self.navigationController pushViewController:customerAndCar animated:YES];
    }];
}



#pragma mark -- 保存

- (void)runBalance
{
    self.accountsModel = [[ICMBalanceAccountsModel alloc] init];
    [self.accountsModel setUpBalanceBasicInfoModelWithBalanceBasicInfoView:self.balanceBasicInfoView];
    [self.accountsModel setupBalanceBasicInfoModelWithBalanceMaintenanceAndPartsView:self.maintenanceAndPartsView];
    if ([ICrEAMTool isVW]) {
        [self.accountsModel setUpBalanceBasicInfoModelWithBalanceInfoView:self.balanceInfoView];
    }else{
        [self.accountsModel setUpBalanceBasicInfoModelWithBalanceInfoSKDView:self.balanceInfoSKDView];
    }
    self.accountsModel.MP3_FILE = self.file;
    
    self.payObjModel = [[ICMBalancePayObjModel alloc] init];
    [self.payObjModel setUpBalanceBasicInfoModelWithBalanceBasicInfoModel:self.basicModel];
    if ([ICrEAMTool isVW]) {
        [self.payObjModel setUpBalanceBasicInfoModelWithBalanceInfoView:self.balanceInfoView];
    }else{
        [self.payObjModel setUpBalanceBasicInfoModelWithBalanceInfoSKDView:self.balanceInfoSKDView];
    }
    
    [self getICMBalanceLabourModels];
    [self getICMBalanceLabourPayObjModels];
    [self getICMBalanceRepairPartModels];
    [self getICMBalanceRepairPartPayObjModels];
    [self getICMBalanceCustomerCoupons];
    
    NSString *url = [NSString stringWithFormat:@"/INFO_ICREAM_WEB/App/addBalanceAccountsApp"];
    [[[ICMRequestManager alloc]init]startPostRequestWithURL:url parameters:[self setupSaveData] inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if (!failText) {
            //保存成功
            [self.view showString:@"结算成功!" forSeconds:1.5f];
            _isAccount = YES;
            self.jiesuanNO = data[@"BALANCE_NO"];
            [self.progressDic setObject:data[@"BALANCE_NO"]?:@"" forKey:@"3"];
            [self addProgressHeaderView];
            [_bottomBarView setButtonDisEnable:0];
            [_bottomBarView setButtonDisEnable:1];
            [_bottomBarView setButtonDisEnable:2];
            [_bottomBarView setButtonDisEnable:3];
            [_bottomBarView setButtonDisEnable:4];
            [_bottomBarView setButtonEnable:5];
            if ([ICrEAMTool isVW]) {
                self.balanceInfoView.userInteractionEnabled = NO;
            }else{
                self.balanceInfoSKDView.userInteractionEnabled = NO;
            }
            self.maintenanceAndPartsView.userInteractionEnabled = NO;
            self.balanceBasicInfoView.userInteractionEnabled = NO;
            self.isPrinted = NO;
            [ICrEAMTool savaOperationReceiptUserName:self.basicModel.OWNER_NAME carSeries:self.basicModel.SERIES_NAME licence:self.basicModel.LICENSE status:@"结算完成" returnTime: StrIsZero_gdm(self.basicModel.END_TIME_SUPPOSED)?@"":[ICrEAMTool getDateHourAndMinSecondWithTimeInterval:self.basicModel.END_TIME_SUPPOSED]];
        }else{
            //保存失败
            [self.view showString:@"结算失败!" forSeconds:1.5f];
        }
    }];
    
}

- (NSMutableDictionary *)setupSaveData
{
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    
    NSDictionary *accountModelDic = [self.accountsModel yy_modelToJSONObject];
    NSArray *accountArray = [[NSArray alloc] initWithObjects:accountModelDic, nil];
    
    NSDictionary *payObjModelDic = [self.payObjModel yy_modelToJSONObject];
    NSArray *payObjArray = [[NSArray alloc] initWithObjects:payObjModelDic, nil];
    
    [dataDic setObject:accountArray forKey:@"TT_BALANCE_ACCOUNTS"];
    [dataDic setObject:payObjArray forKey:@"TT_BALANCE_PAYOBJ"];
    
    
    [dataDic setObject:[self.labourModelArray yy_modelToJSONObject] forKey:@"TT_BALANCE_LABOUR"];
    [dataDic setObject:[self.labourPayObjModelArray yy_modelToJSONObject] forKey:@"TT_BALANCE_LABOUR_PAYOBJ"];
    [dataDic setObject:[self.repairPartModelArray yy_modelToJSONObject] forKey:@"TT_BALANCE_REPAIR_PART"];
    [dataDic setObject:[self.repairPartPayObjModelArray yy_modelToJSONObject] forKey:@"TT_BALANCE_REPAIR_PART_PAYOBJ"];
    [dataDic setObject:[self.customerCouponArray yy_modelToJSONObject] forKey:@"TT_CUSTOMER_COUPON"];
    
    return dataDic;
}

#pragma mark --balanceInfo点击
- (void)clickMemberBtn{
    if (self.basicModel.VIN) {
        [self memberInfo];
    }
}

- (void)clickMemberBtnWithCardNO:(NSString *)cardNO{
    [self memberSkdWithCardNO:cardNO];
}

- (void)memberInfo{
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:self.basicModel.VIN forKey:@"VIN"];
    [parameters setObject:self.basicModel.RO_NO forKey:@"RO_NO"];
    [manager startGetRequestWithURL:IcreamPoint parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue] == 200) {
            if (IsArr(data[@"TT_HQ_MEMBER"])) {
                ICMProxyMemberModel *model = [ICMProxyMemberModel yy_modelWithDictionary:data[@"TT_HQ_MEMBER"][0]];
                ICMMemberView *MV = [[ICMMemberView alloc]initWithFrame:CGRectMake((ScreenWidth-ActualWidth(600))/2, (ScreenHeight-ActualHeight(400))/2, ActualWidth(600), ActualHeight(400))];
                CornerRadius(MV, RadiusValue);
                BorderWidth(MV, 1.0);
                BorderColor(MV, BorderColor_Gray_Hex);
                MV.memberCard.contentText = model.CARD_NO;
                MV.memberName.contentText = model.CARD_NAME;
                MV.memberStatus.contentText = model.CARD_STATUS;
                MV.memberType.contentText = model.CARD_TYPE;
                MV.totalPoint.contentText = model.TOTAL_POINT;
                MV.availablePoint.contentText = model.AVAILABLE_POINT;
                MV.frozenPoint.contentText = model.FROZEN_POINT;
                self.balanceInfoView.withholdIntegralView.contentText = model.CONVERT_SCORE;
                self.balanceInfoView.exchangeAmountView.contentText = model.PART_SALES_AMOUNT;
                self.balanceInfoView.VWIntegralAmountView.contentText = model
                .AVAILABLE_AMOUNT;
                self.balanceInfoView.verificationBtn.alpha = 1;
                self.balanceInfoView.verificationBtn.enabled = YES;
                self.balanceInfoView.VWIntegralView.contentText = model.AVAILABLE_POINT;
                self.balanceInfoView.MEMBER_PROPERTY_NAME = model.MEMBER_PROPERTY;
                self.balanceInfoView.HQ_VW_CARD_TYPE = model.CARD_TYPE;
                //                self.balanceInfoView.HQ_VW_CARD_TYPE = model.CARD_TYPE;
                self.memberView = MV;
                [Window addSubview:self.blankView];
                [Window addSubview:self.memberView];
            }
        }else{
            [self.view showString:@"根据VIN码找不到会员卡信息！" forSeconds:1.5];
        }
    }];
}

- (void)memberSkdWithCardNO:(NSString *)cardNO{
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:self.basicModel.VIN forKey:@"VIN"];
    [parameters setObject:cardNO forKey:@"CARD_NO"];
    [manager startGetRequestWithURL:MemberSkd parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue] == 200) {
            if (IsArr(data[@"TT_MEMBER_SKD"])) {
                ICMProxyMemberSKDModel *model = [ICMProxyMemberSKDModel yy_modelWithDictionary:data[@"TT_MEMBER_SKD"][0]];
                ICMMemberView *MV = [[ICMMemberView alloc]initWithFrame:CGRectMake((ScreenWidth-ActualWidth(600))/2, (ScreenHeight-ActualHeight(400))/2, ActualWidth(600), ActualHeight(400))];
                CornerRadius(MV, RadiusValue);
                BorderWidth(MV, 1.0);
                BorderColor(MV, BorderColor_Gray_Hex);
                if (model.IS_USE && ![model.IS_USE isEqualToString:@"0"]) {
                    self.balanceInfoSKDView.verificationView.borderView.backgroundColor = TextFeildBackgroundColor_OffWhite;
                    self.balanceInfoSKDView.verificationView.userInteractionEnabled = YES;
                    MV.availablePoint.contentText = @"开";
                    self.balanceInfoSKDView.verificationBtn.alpha = 1.0;
                    self.balanceInfoSKDView.verificationBtn.enabled = YES;
                    self.isUse = @"1";
                }else{
                    self.balanceInfoSKDView.verificationView.borderView.backgroundColor = TextFeildBackgroundColor_Gray;
                    self.balanceInfoSKDView.verificationView.userInteractionEnabled = NO;
                    MV.availablePoint.contentText = @"关";
                    self.balanceInfoSKDView.verificationBtn.alpha = 0.5;
                    self.balanceInfoSKDView.verificationBtn.enabled = NO;
                    self.isUse = @"0";
                }
                MV.memberCard.contentText = model.CARD_NO;
                MV.memberName.contentText = model.CARD_OWNER;
                MV.memberStatus.contentText = model.SST_CODE;
                MV.memberType.contentText = model.SST_NAME;
                MV.totalPoint.contentText = model.HQ_SCORE;
                MV.frozenPoint.contentText = model.SST_SCORE;
                MV.isBinding.contentText = [model.IS_BIND isEqualToString:@"1"]?@"是":@"否";
                self.memberView = MV;
                self.balanceInfoSKDView.SKDAmountView.contentText = model.HQ_SCORE;
                self.balanceInfoSKDView.SSTAmountView.contentText = model.SST_SCORE;
                [Window addSubview:self.blankView];
                [Window addSubview:self.memberView];
            }
        }else{
            [self.view showString:@"根据会员卡号找不到会员信息！" forSeconds:1.5];
        }
    }];
}

- (UIView *)blankView{
    if (!_blankView) {
        _blankView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _blankView.backgroundColor = [UIColor clearColor];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideBlankView)];
        [_blankView addGestureRecognizer:tap];
    }
    return _blankView;
}

- (void)hideBlankView{
    [self.blankView removeFromSuperview];
    [self.levelView removeFromSuperview];
    if (self.memberView) {
        [self.memberView removeFromSuperview];
    }
    for (UIView *view in self.blankView.subviews) {
        [view removeFromSuperview];
    }
}

#pragma mark -- 提交判断
- (BOOL)checkFormData{
    if (StrIsZero_gdm(self.balanceBasicInfoView.useKindView.contentText)) {
        [self.view showString:@"车辆使用性质为空，请先维护车主车辆信息！" forSeconds:1.5];
        return NO;
    }
    if (self.balanceInfoView.VWUseIntegralView.contentText && [self.balanceInfoView.VWUseIntegralView.contentText doubleValue]>0) {
        if (StrIsZero_gdm(self.balanceInfoView.verificationView.contentText)) {
            [self.view showString:@"请输入收到的短信验证码！" forSeconds:1.5];
            return NO;
        }
        if (![self.balanceInfoView.verification isEqualToString:self.balanceInfoView.verificationView.contentText]) {
            [self.view showString:@"短信验证码有误，请重新输入！" forSeconds:1.5];
            return NO;
        }
    }
    
    if (StrIsZero_gdm(self.balanceBasicInfoView.vinNumberView.contentText)) {
        [self.view showString:@"VIN码不能为空" forSeconds:1.5];
        return NO;
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.plateNumberView.contentText)) {
        [self.view showString:@"车牌号不能为空" forSeconds:1.5];
        return NO;
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.modelCodeView.contentText)) {
        [self.view showString:@"车型号不能为空" forSeconds:1.5];
        return NO;
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.salesDateView.contentText)) {
        [self.view showString:@"购车发票日期不能为空" forSeconds:1.5];
        return NO;
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.useKindView.contentText)) {
        [self.view showString:@"使用性质不能为空" forSeconds:1.5];
        return NO;
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.accountsTypeView.contentText)) {
        [self.view showString:@"结算方式不能为空" forSeconds:1.5];
        return NO;
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.levelView.contentText)) {
        [self.view showString:@"行管类型不能为空" forSeconds:1.5];
        return NO;
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.proxyNOView.contentText)) {
        [self.view showString:@"委托书号不能为空" forSeconds:1.5];
        return NO;
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.createDateView.contentText)) {
        [self.view showString:@"开单日期不能为空" forSeconds:1.5];
        return NO;
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.ownerNameView.contentText)) {
        [self.view showString:@"车主姓名不能为空" forSeconds:1.5];
        return NO;
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.repairTypeView.contentText)) {
        [self.view showString:@"维修类型不能为空" forSeconds:1.5];
        return NO;
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.deliverNameView.contentText)) {
        [self.view showString:@"送修人姓名不能为空" forSeconds:1.5];
        return NO;
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.deliverMobileView.contentText)) {
        [self.view showString:@"送修人手机不能为空" forSeconds:1.5];
        return NO;
    }
    
    if (self.balanceBasicInfoView.isVisit == YES) {
        if (StrIsZero_gdm(self.balanceBasicInfoView.visitDateView.contentText)) {
            [self.view showString:@"回访时间不能为空" forSeconds:1.5];
            return NO;
        }
        if (StrIsZero_gdm(self.balanceBasicInfoView.visitTypeView.contentText)) {
            [self.view showString:@"回访方式不能为空" forSeconds:1.5];
            return NO;
        }
    }else{
        if (StrIsZero_gdm(self.balanceBasicInfoView.visitReasonView.contentText)) {
            [self.view showString:@"不回访原因不能为空" forSeconds:1.5];
            return NO;
        }
    }
    if (StrIsZero_gdm(self.balanceBasicInfoView.oldPartView.contentText)) {
        [self.view showString:@"旧件处理不能为空" forSeconds:1.5];
        return NO;
    }
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag == 101)
    {
        if(buttonIndex == 0)
        {
            //否
        }
        else
        {
            //是 放弃
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
    if ([alertView.message isEqualToString:@"确认进行结算？"]) {
        if (buttonIndex == 1) {
            
            if (self.haveRecord) {
                [self.view showString:@"录音结束" forSeconds:1.5];
                [self clickStopBtn];
            }else{
                //结算
                if ([self checkFormData]) {
                    [self runBalance];
                }
            }
        }
    }else if([alertView.message isEqualToString:@"结算单未打印，确认返回？"]){
        if (buttonIndex == 1){
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}


#pragma mark -- 录音功能

- (AVAudioRecorder *)audioRecorder{
    if (!_audioRecorder) {
        //创建录音文件保存路径
        NSURL *url = [NSURL URLWithString:micTempPath];
        //创建录音格式设置
        NSDictionary *setting = [self getAudioSetting];
        //创建录音机
        NSError *error = nil;
        _audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate = self;
        [_audioRecorder peakPowerForChannel:0];
        _audioRecorder.meteringEnabled = YES;//如果要监控声波则必须设置为YES
        if (error) {
            self.haveRecord = NO;
            self.bottomBarView.recorderLabel.text = @"录 音";
            [self.view showString:@"录音失败" forSeconds:1.5];
            return nil;
        }
    }
    return _audioRecorder;
}

- (AVAudioPlayer *)audioPlayer {
    if (!_audioPlayer) {
        NSURL *url = [NSURL URLWithString:micTempPath];
        NSError *error = nil;
        _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
        _audioPlayer.numberOfLoops = 0;
        if (![_audioPlayer prepareToPlay]) {
        };
        if (error) {
            return nil;
        }
    }
    return _audioPlayer;
}

- (void)setAudioAndPlayer{
    [self setAudioSession];
    //    self.couldRecord = [self.audioRecorder prepareToRecord];
}

- (void)setAudioSession {
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    
    if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
        [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
            if (granted) {
                NSError *error;
                [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
                if (error) {
                    error = nil;
                }
                [audioSession setActive:YES error:&error];
                if (error) {
                    
                }
                self.couldRecord = YES;
            } else {
                self.couldRecord = NO;
            }
        }];
    }
    
}

- (NSDictionary *)getAudioSetting{
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    //设置录音格式
    [dicM setObject:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];
    //设置录音采样率，8000是电话采样率，对于一般录音已经够了
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    //设置通道,这里采用单声道
    [dicM setObject:@(1) forKey:AVNumberOfChannelsKey];
    //每个采样点位数,分为8、16、24、32
    [dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];
    //    //是否使用浮点数采样
    //    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    [dicM setObject:@(AVAudioQualityMax) forKey:AVEncoderAudioQualityKey];
    return dicM;
}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    [self uploadMusic];
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error {
    [self runBalance];
}

- (void)clickRecordBtn{
    if (self.couldRecord){
        [self.audioRecorder record];
    }
}

- (void)clickStopBtn{
    
    [self.audioRecorder stop];
    
}

- (void)clickPauseBtn{
    if (self.couldRecord){
        [self.audioRecorder pause];
    }
}

#pragma mark -- 授权页面
- (ICMLevelView *)levelView
{
    if(!_levelView)
    {
        _levelView = [[ICMLevelView alloc] initWithFrame:CGRectMake((Window.bounds.size.width-300)/2, (Window.bounds.size.height-320)/2, 300, 320)];
    }
    _levelView.delegate = self;
    return _levelView;
}

//ICMLevelViewDelegate
- (void)levelCommitWithName:(NSString *)name WithPs:(NSString *)ps
{
    [self hideBlankView];
    [self.levelView removeFromSuperview];
    [self getDiscountModeData:name WithPS:ps WithType:0];
}
- (void)levelCancel
{
    [self hideBlankView];
    [self.levelView removeFromSuperview];
}

- (void)getDiscountModeData:(NSString *)ownerCode WithPS:(NSString *)ps WithType:(int)type
{
    NSString *url = [NSString stringWithFormat:@"/INFO_ICREAM_WEB/App/queryUserFunctionPurview"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:ownerCode forKey:@"EMPLOYEE_NO"];
    [parameters setObject:ps forKey:@"PASSWORD"];
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    [manager startGetRequestWithURL:url parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue] == 200) {
            if ([data[@"MSG"] isEqualToString:@"12781001"]) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确认进行结算？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
                [alert show];
                
                self.isAuthorization = YES;
            }else{
                self.isAuthorization = NO;
                [self.view showString:@"该用户无结算权限" forSeconds:1.5];
            }
        }else{
        }
    }];
}

//各页面值变化通知
- (void)viewValueChanged:(NSNotification *)notification
{
    self.hasViewValueChanged = YES;
}

- (void)setHasViewValueChanged:(BOOL)hasViewValueChanged
{
    _hasViewValueChanged = hasViewValueChanged;
    super.super_hasViewValueChanged = _hasViewValueChanged;
}


//获取优惠券信息
- (void)getData:(NSString *)ownerCode
{
    if(!ownerCode)
        ownerCode = @"";
    NSString *url = [NSString stringWithFormat:@"/INFO_ICREAM_WEB/App/queryCustomer"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:ownerCode forKey:@"QUERY_CONDITION"];
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    [manager startGetRequestWithURL:url parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        [self.couponViewController.dataArray removeAllObjects];
        if (IsArr(data[@"TT_CUSTOMER_COUPON"])) {
            NSArray *array = data[@"TT_CUSTOMER_COUPON"];
            for(int i = 0;i<array.count;i++)
            {
                ICMBalanceCouponModel *model = [ICMBalanceCouponModel yy_modelWithDictionary:array[i]];
                for (ICMBalanceCouponModel *selectModel in self.selectedDataArray) {
                    if ([model.ITEM_ID isEqualToString:selectModel.ITEM_ID]) {
                        model = selectModel;
                    }
                }
                [self.couponViewController.dataArray addObject:model];
            }
        }
        [self.couponViewController refreshView];
    }];
}

#pragma mark -- 点击验证码
- (void)clickVerificationBtn{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:self.balanceInfoView.model.OWNER_MOBILE?:@"" forKey:@"MOBILE"];
    [parameters setObject:self.balanceInfoView.model.RO_NO?:@"" forKey:@"BUSINESS_NO"];
    [parameters setObject:self.balanceInfoView.model.HQ_VW_CARD_ID?:@"" forKey:@"CARD_ID"];
    [parameters setObject:self.balanceInfoView.model.VIN?:@"" forKey:@"VIN"];
    [parameters setObject:self.balanceInfoView.VWUseIntegralView.contentText?:@"0" forKey:@"USE_CREDIT"];
    [parameters setObject:self.balanceInfoView.model.OWNER_NAME?:@"" forKey:@"CUSTOMER_NAME"];
    [[[ICMRequestManager alloc]init]startPostRequestWithURL:SendMessageFromApp parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue]== 200) {
            self.balanceInfoView.verification = data[@"VERIFY_CODE"];
            [self.balanceInfoView startTimer];
        }
    }];
}

- (void)clickSKDVerificationBtn{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:self.balanceInfoSKDView.model.RO_NO?:@"" forKey:@"BUSINESS_NO"];
    [parameters setObject:self.balanceInfoSKDView.cardNoView.contentText?:@"" forKey:@"CARD_ID"];
    [parameters setObject:self.balanceInfoSKDView.model.VIN?:@"" forKey:@"VIN"];
    [[[ICMRequestManager alloc]init]startGetRequestWithURL:GetGeneratorVerification parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue]== 200) {
            self.balanceInfoSKDView.verificationView.contentText = data[@"TT_GEN_CODE"][0][@"GEN_CODE"];
            [self.balanceInfoSKDView startTimer];
        }
    }];
    
}

#pragma mark -- 增加优惠券
- (void)startToSaveCouponToServer{
    if(self.balanceAddCouponView.dataArray.count == 0)
        return;
    NSString *url = [NSString stringWithFormat:@"/INFO_ICREAM_WEB/App/addCustomer"];
    [[[ICMRequestManager alloc]init]startPostRequestWithURL:url parameters:[self.balanceAddCouponView setupSaveData] inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if (!failText) {
            //保存成功
            [self.balanceAddCouponView showString:@"保存成功!" forSeconds:1.5f];
            [self.balanceAddCouponView removeFromSuperview];
        }else{
            //保存失败
            [self.balanceAddCouponView showString:@"保存失败!" forSeconds:1.5f];
        }
    }];
}

#pragma mark -- 获取折扣力度

- (void)getMaintenanceAndPartsDiscountModeData:(NSString *)ownerCode WithPS:(NSString *)ps WithType:(int)type
{
    
    
    self.maintenanceAndPartsView.myLabourDisLimit = 1.00;
    self.maintenanceAndPartsView.myPartDisLimit = 1.00;
    self.maintenanceAndPartsView.otherLabourDisLimit = 1.00;
    self.maintenanceAndPartsView.otherPartDisLimit = 1.00;
    
    NSString *url = [NSString stringWithFormat:@"/INFO_ICREAM_WEB/App/queryDiscountModel"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:ownerCode forKey:@"EMPLOYEE_NO"];
    [parameters setObject:ps forKey:@"PASSWORD"];
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    [manager startGetRequestWithURL:url parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if (failText || data[@"MSG"]) {
            self.maintenanceAndPartsView.workingRatioView.contentTextFeild.text = self.maintenanceAndPartsView.tureVauleLabourDis;
            self.maintenanceAndPartsView.partsRatioView.contentTextFeild.text = self.maintenanceAndPartsView.tureVaulePartDis;
            return ;
        }
        
        if(IsArr(data[@"TM_DISCOUNT_MODE"]))
        {
            self.maintenanceAndPartsView.disArray = [NSMutableArray arrayWithArray:data[@"TM_DISCOUNT_MODE"]];
            if (type == 0) {
                self.maintenanceAndPartsView.firstArray = [NSMutableArray arrayWithArray:data[@"TM_DISCOUNT_MODE"]];
            }
            NSMutableArray *nameList = [[NSMutableArray alloc] init];
            NSMutableArray *noList = [[NSMutableArray alloc] init];
            for(int i =0;i<self.maintenanceAndPartsView.disArray.count;i++)
            {
                [nameList addObject:self.maintenanceAndPartsView.disArray[i][@"DISCOUNT_MODE_NAME"]];
                [noList addObject:self.maintenanceAndPartsView.disArray[i][@"DISCOUNT_MODE_CODE"]];
                
                double labour = [self.maintenanceAndPartsView.disArray[i][@"LABOUR_AMOUNT_DISCOUNT"] doubleValue];
                double part = [self.maintenanceAndPartsView.disArray[i][@"REPAIR_PART_DISCOUNT"] doubleValue];
                if(type == 0)
                {
                    if(labour < self.maintenanceAndPartsView.myLabourDisLimit)
                        self.maintenanceAndPartsView.myLabourDisLimit = labour;
                    if(part < self.maintenanceAndPartsView.myPartDisLimit)
                        self.maintenanceAndPartsView.myPartDisLimit = part;
                }
                if(type == 1)
                {
                    if(labour < self.maintenanceAndPartsView.otherLabourDisLimit){
                        self.maintenanceAndPartsView.otherLabourDisLimit = labour;
                        if (self.maintenanceAndPartsView.otherLabourDisLimit > [self.maintenanceAndPartsView.workingRatioView.contentTextFeild.text doubleValue]) {
                            self.maintenanceAndPartsView.workingRatioView.contentTextFeild.text = self.maintenanceAndPartsView.tureVauleLabourDis;
                        }
                    }
                    
                    if(part < self.maintenanceAndPartsView.otherPartDisLimit){
                        self.maintenanceAndPartsView.otherPartDisLimit = part;
                        if (self.maintenanceAndPartsView.otherPartDisLimit > [self.maintenanceAndPartsView.partsRatioView.contentTextFeild.text doubleValue]) {
                            self.maintenanceAndPartsView.partsRatioView.contentTextFeild.text = self.maintenanceAndPartsView.tureVaulePartDis;
                        }
                    }
                }
            }
            
            if (type == 1) {
                if (self.maintenanceAndPartsView.otherLabourDisLimit > [self.maintenanceAndPartsView.workingRatioView.contentTextFeild.text doubleValue]) {
                    self.maintenanceAndPartsView.workingRatioView.contentTextFeild.text = self.maintenanceAndPartsView.tureVauleLabourDis;
                }
                if (self.maintenanceAndPartsView.otherPartDisLimit > [self.maintenanceAndPartsView.partsRatioView.contentTextFeild.text doubleValue]) {
                    self.maintenanceAndPartsView.partsRatioView.contentTextFeild.text = self.maintenanceAndPartsView.tureVaulePartDis;
                }
            }
            
            if(type == 0)
            {
                self.maintenanceAndPartsView.discountModeView.clickDataArray = nameList;
                self.maintenanceAndPartsView.discountModeView.clickDataNoArray = noList;
                
            }
            self.maintenanceAndPartsView.levelNo = ownerCode;
        }
        [self.maintenanceAndPartsView calculateRatioPrice];
        
    }];
}



@end
